package com.zimo.download.thread;

import com.zimo.download.Download;
import com.zimo.download.DownloadImpl;
import com.zimo.download.info.PointerOffset;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URL;

/**
 * 多线程下载只管开启多线程，他由ThreadManagerDownload调用
 * 如果你不想用ThreadManagerDownload调用的话那么你可以，直接调用它，但是文件分块有些麻烦，尽管ThreadManagerDownload有方法可以进行分块，但那是他私有的
 */
public class ThreadDownload implements Download , Runnable {

    private URL url = null; //url地址
    private String filePath = "C:\\Users\\Administrator\\Downloads\t";
    private Download download= null;
    private PointerOffset pointerOffset=null;

    //获取logger对象： 传入当前类的class，这样代表这个类输出的日志信息
    private Logger logger = Logger.getLogger(ThreadDownload.class);
    /**
     *
     * @param url   文件链接
     * @param pointerOffset   线程数
     */
    public ThreadDownload(URL url, String filePath, PointerOffset pointerOffset, Download downloadImpl){
        this.filePath=filePath;
        this.url=url;
        this.pointerOffset=pointerOffset;
        this.download=downloadImpl;
    }



    @Override
    public void run() {
        //下载
//        synchronized (this) {
            try {
//                System.out.println(download);
                download.startDownload(url,filePath,pointerOffset);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(Thread.currentThread().getName()+"线程未能成功开始下载");
            }
//        }
    }


    @Override
    public boolean startDownload(URL url, String filePath, PointerOffset pointerOffset) throws IOException {
        return false;
    }

    /**
     * 暂停所有线程
     */
    @Override
    public boolean stopDownload(String name) {
        new DownloadImpl().stopDownload(name);
        return true;
    }

    @Override
    public int getFinishThread() {
        return download.getFinishThread();
    }

    @Override
    public long getDownloadingFileSize() {
        return download.getDownloadingFileSize();
    }

}
